<?php
namespace app\common\tool;


use app\common\model\Post as PostModel;
use app\common\model\PostClass as PostClassModel;
use app\common\tool\Tool;
use app\common\model\SolutionCat as SolutionCatModel;
use app\common\model\Solution as SolutionModel;
use app\common\model\ProductCat as ProductCatModel;
use app\common\model\Product as ProductModel;
use app\common\model\ProductData as ProductDataModel;
use app\common\model\CustomerCase as CustomerCaseModel;
use app\common\model\CaseCat as CaseCatModel;
use app\common\model\ProductFuncat as ProductFuncatModel;
use app\common\model\Anchor as AnchorModel;
use app\common\tool\Page;
use think\Config;
use think\Request;

/**
 * 前端页面的所有查询都来自与本查询类 这样可以保持前端的独立性
 * Class Query
 * @package app\common\tool
 */
class Query{

    protected $store = [];

    public function menu(){

    }


    /**
     * 文章的目录
     */
    public function getPostClass(){
        if(isset($this->store['getPostClass'])){
            return $this->store['getPostClass'];
        }
        $postClass = PostClassModel::all();
        $postClass = collection($postClass)->toArray();

        $tool = new Tool();
        $postClass = $tool -> changeArrayKey($postClass);

        foreach($postClass as $key => $val){
            if(isset($postClass[$val['pid']])){
                $postClass[$val['pid']]['sub'][$key] = $val;
                unset($postClass[$key]);
            }
        }
        $this->store['getPostClass'] = $postClass;

        return $this->store['getPostClass'];
    }

    public function getPostsByClass($classId){
        if(isset($this->store['getPostsByClass'][$classId])){
            return $this->store['getPostsByClass'][$classId];
        }
        $classIds = PostClassModel::where('pid',$classId)->column('id');
        array_push($classIds,$classId);

        return $this->store['getPostsByClass'][$classId] = PostModel::whereIn('pc_id',$classIds)->order('id desc')->paginate(6);

    }


    public function getPost($id){
        if(isset($this->store['getPost'][$id])){
            return $this->store['getPost'][$id];
        }
        $post = PostModel::find($id);
        $anchors = AnchorModel::all();
        $anchors = collection($anchors)->toArray();
        foreach( $anchors as $key => $val ){
            $post->postData->content = preg_replace('/'.$val['name'].'/','<a href="'.$val['url'].'" class="replace">'.$val['name'].'</a>',$post->postData->content,1);
        }

        return $this->store['getPost'] = $post;
    }

    public function getNeighbour($id){
        if(isset($this->store['getNeighbour'][$id])){
            return $this->store['getNeighbour'][$id];
        }
        $result = [];
        $result['front'] = PostModel::where('id','<',$id)->order('id desc')->find();
        $result['next'] = PostModel::where('id','>',$id)->order('id asc')->find();
        return $this->store['getNeighbour'][$id] = $result;
    }

    /**
     * 看来要弄排序字段
     * @param int $pageSize
     * @return \think\Paginator
     */
    public function getSolutionCat($pageSize=4){
        if(isset($this->store['getSolutionCat'][$pageSize])){
            return $this->store['getSolutionCat'][$pageSize];
        }else{
            return $this->store['getSolutionCat'][$pageSize] = SolutionCatModel::order('id desc')->paginate($pageSize);
        }
    }

    public function getSolutionCatOne($catid){
        if(isset($this->store['getSolutionCatOne'][$catid])){
            return $this->store['getSolutionCatOne'][$catid];
        }else{
            return $this->store['getSolutionCatOne'][$catid] = SolutionCatModel::find($catid);
        }
    }

    public function getSolutions($catid=0,$pageSize=4){
        if(isset($this->store['getSolutions'][$catid."-".$pageSize])){
            return $this->store['getSolutions'][$catid."-".$pageSize];
        } else{
            if(!$catid){
                return $this->store['getSolutions'][$catid."-".$pageSize] = SolutionModel::order('id desc')->paginate($pageSize);
            }
            return $this->store['getSolutions'][$catid."-".$pageSize] = SolutionModel::where('catid',$catid)->order('id desc')->paginate($pageSize);
        }
    }

    public function getSolution($id){
        if(isset($this->store['getSolution'][$id])){
            return $this->store['getSolution'][$id];
        }else{
            return $this->store['getSolution'][$id] = SolutionModel::find($id);
        }
    }

    public function getAssocProductsForSolution($id){
        if(isset($this->store['getAssocProductsForSolution'][$id])){
            return $this->store['getAssocProductsForSolution'][$id];
        }
        $assoc = SolutionModel::where('id',$id)->value('assoc');
        $assoc = json_decode($assoc);
        if(!$assoc) $assoc = [];

        $assocProducts = ProductModel::whereIn('id',$assoc)->select();
        return $this->store['getAssocProductsForSolution'][$id] = $assocProducts;
    }


    //产品部分--------------------------------------------------------------------------------------

    public function getAllProduct(){
        if(isset($this->store['getAllProduct'])){
            return $this->store['getAllProduct'];
        }
        $products = ProductModel::all();
        $products = collection($products)->toArray();
        $tool = new Tool();
        $products = $tool->changeArrayKey($products);
        return $this->store['getAllProduct'] = $products;
    }


    public function getProductCat($catway,$pid = 0){

        if(isset($this->store['getProductCat'][$catway])){
            return $this->store['getProductCat'][$catway];
        }
        $productCats = ProductCatModel::all(['catway'=>$catway]);
        $productCats = collection($productCats)->toArray();
        $tool = new Tool();
        $productCats = $tool->changeArrayKey($productCats);
        $productCats = $tool->findSub($productCats,$pid);
        $this->store['getProductCat'][$catway] = $productCats;

        return  $this->store['getProductCat'][$catway];
    }

    public function getProductCatById($id){
        if(isset($this->store['getProductCatById'][$id])){
            return $this->store['getProductCatById'][$id];
        }
        return  $this->store['getProductCatById'][$id] = ProductCatModel::find($id);
    }

    /**
     * @param string $type fun_cat|sys_cat
     * @return array
     */
    public function getProductsForCat($type = 'fun_cat'){
        if(isset($this->store['getProductsForCat'][$type])){
            return $this->store['getProductsForCat'][$type];
        }
        $products = ProductModel::all();
        $products = collection($products)->toArray();
        //按照类目分类
        $productsByClass = [];
        foreach($products as $key => $val ){
            if(!isset($productsByClass[$val[$type]])){
                $productsByClass[$val[$type]] = [];
            }

            array_push($productsByClass[$val[$type]],$val);
        }

        return $this->store['getProductsForCat'][$type] = $productsByClass;

    }

    /**
     * 找到某一系统分类下的所有产品
     * @param $catid
     */
    public function getProductsForSysCat($catid){
        if(isset($this->store['getProductsForSysCat'][$catid])){
            return $this->store['getProductsForSysCat'][$catid];
        }
        $cats = ProductCatModel::where('pid',$catid)->field('id')->order('id desc')->select();
        $cats = collection($cats)->toArray();
        $cats = array_column($cats,'id');
        array_push($cats,$catid);
        $cats = implode(',',$cats);
        $products = ProductModel::where("sys_cat","in",$cats)->order('sort desc')->select();
        $this->store['getProductsForSysCat'][$catid] = $products;
        return $this->store['getProductsForSysCat'][$catid];
    }

    public function getTopSys(){
        return ProductCatModel::where('catway','sys')->where('pid','!=')->select();
    }

    public function getProductsForFuncat(){
        if(isset($this->store['getProductsForFuncat'])){
            return $this->store['getProductsForFuncat'];
        }

        //按照类目分类
        $productsByClass = [];
        $productFuncats = ProductFuncatModel::all();
        $productFuncats = collection($productFuncats)->toArray();
        foreach($productFuncats as $key => $val ){
            if(!isset($productsByClass[$val['funcatid']])){
                $productsByClass[$val['funcatid']] = [];
            }
            array_push($productsByClass[$val['funcatid']],$val['productid']);
        }



        return $this->store['getProductsForFuncat'] = $productsByClass;
    }


    public  function  getProductBasic($productId){
        if(isset($this->store['getProductBasic'][$productId])){
            return $this->store['getProductBasic'];
        }
        $product = ProductModel::find($productId);
        $sku = ProductDataModel::where('productid',$product->id)->order('id asc')->select();

        $basicInfo = [
            'product'=>$product,
            'sku'=>$sku
        ];

        $this->store['getProductBasic'][$productId] = $basicInfo;
        return $this->store['getProductBasic'][$productId];
    }

    public function getProductEx($productId,$skuId){
        if(isset($this->store['getProductEx'][$productId][$skuId])){
            return $this->store['getProductEx'][$productId][$skuId];
        }

        $this->store['getProductEx'][$productId][$skuId] = ProductDataModel::where('productid',$productId)->where('id',$skuId)->find();
        return $this->store['getProductEx'][$productId][$skuId];
    }


    /**
     * 推荐的产品
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getRecommendProduct(){
        if(isset($this->store['getRecommendProduct'])){
            return $this->store['getRecommendProduct'];
        }

        return $this->store['getRecommendProduct'] = ProductModel::where('is_recommend',1)->select();
    }

    /**
     * 关联的产品
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getAssocProducts($id){
        if(isset($this->store['getRecommendProduct'][$id])){
            return $this->store['getRecommendProduct'][$id];
        }
        $assoc = ProductModel::where('id',$id)->value('assoc');
        $assoc = json_decode($assoc);
        if(!$assoc) $assoc = [];

        $assocProducts = ProductModel::whereIn('id',$assoc)->select();
        return $this->store['getRecommendProduct'][$id] = $assocProducts;
    }


    //案例部分-----------------------------------------------------


    public function getCustomerCaseCat(){
        if(isset($this->store['getCustomerCaseCat'])){
            return $this->store['getCustomerCaseCat'];
        }

        $caseCats = CaseCatModel::all();
        $caseCats = collection($caseCats)->toArray();
        $tool = new Tool();
        $caseCats = $tool->changeArrayKey($caseCats);
        $caseCats = $tool->findSub($caseCats,0);
        $this->store['getCustomerCaseCat'] = $caseCats;

        return $this->store['getCustomerCaseCat'];
    }

    /**
     * 获取一个分类信息
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getCustomerCaseCatById($id){
        if(isset($this->store['getCustomerCaseCatById'][$id])){
            return $this->store['getCustomerCaseCatById'][$id];
        }

        return $this->store['getCustomerCaseCatById'][$id] = CaseCatModel::find($id);
    }


    /**
     * 获取子类列表
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public function getCustomerCaseCatSub($id){
        if(isset($this->store['getCustomerCaseCatSub'][$id])){
            return $this->store['getCustomerCaseCatSub'][$id];
        }

        return $this->store['getCustomerCaseCatSub'][$id] = CaseCatModel::where(['pid'=>$id])->select();
    }


    /**
     * 找出分类及子类的数据
     * @param int $catId
     * @param int $pageSize
     * @return mixed
     */
    public function getCustomerCase($catId=0,$pageSize=9){
        if(isset($this->store['getCustomerCase'][$catId][$pageSize])){
            return $this->store['getCustomerCase'][$catId][$pageSize];
        }
        if(!$catId){
            $this->store['getCustomerCase'][$catId][$pageSize] = CustomerCaseModel::order('id desc')->paginate($pageSize);
        }else{
            $caseCats = CaseCatModel::all();
            $searchCaseCats = [];
            foreach($caseCats as $key => $val){
                if($val['pid'] == $catId || $val['id'] == $catId){
                    array_push($searchCaseCats,$val['id']);
                }
            }

            $this->store['getCustomerCase'][$catId][$pageSize] = CustomerCaseModel::whereIn('catid',$searchCaseCats)->paginate($pageSize);
        }


        return $this->store['getCustomerCase'][$catId][$pageSize];

    }


    public function getCustomerCaseContent($id){
        if(isset($this->store['getCustomerCaseContent'][$id])){
            return $this->store['getCustomerCaseContent'][$id];
        }

        $this->store['getCustomerCaseContent'][$id] =CustomerCaseModel::find($id);

        return $this->store['getCustomerCaseContent'][$id];
    }

    public function getCustomerCasesByIds($ids){
        $key = md5(json_encode($ids));
        if(isset($this->store['getCustomerCasesByIds'][$key])){
            return $this->store['getCustomerCasesByIds'][$key];
        }

        return $this->store['getCustomerCasesByIds'][$key] = CustomerCaseModel::whereIn('id',$ids)->select();
    }

    public function getAssocProductsForCustomer($id){
        if(isset($this->store['getAssocProductsForCustomer'][$id])){
            return $this->store['getAssocProductsForCustomer'][$id];
        }
        $assoc = CustomerCaseModel::where('id',$id)->value('assoc');
        $assoc = json_decode($assoc);
        if(!$assoc) $assoc = [];

        $assocProducts = ProductModel::whereIn('id',$assoc)->select();
        return $this->store['getAssocProductsForCustomer'][$id] = $assocProducts;
    }


    /**
     * 根据关键词搜索 产品 文章 解决方案等等都放在一个页面
     * @param $keyword string
     * @param $page int
     * @param  $pageSize int
     * @return array
     */
    public function search($keyword,$page=1,$pageSize = 6){

        //整合所有的搜索 再进行分页
        $postResult = PostModel::where('title','like','%'.$keyword.'%')->select();
        $productResult = ProductModel::where('name','like','%'.$keyword.'%')->select();
        $solutionResult = SolutionModel::where('title','like','%'.$keyword.'%')->select();

        $productResult = collection($productResult)->toArray();
        $postResult = collection($postResult)->toArray();
        $solutionResult = collection($solutionResult)->toArray();

        foreach($productResult as $key => $val ){
            $productResult[$key]['resultType'] = 'product';
        }
        foreach($postResult as $key => $val ){
            $postResult[$key]['resultType'] = 'post';
        }
        foreach($solutionResult as $key => $val ){
            $solutionResult[$key]['resultType'] = 'solution';
        }

        $result = array_merge($productResult,$postResult,$solutionResult);

        $total = count($result);
        $paginator = new Page();
        $paginator->init($total, $pageSize);
        $paginator->setTemplate('<div class="list-nav"><a title="Total record">&nbsp;<b>{pagenum}</b></a>&nbsp;&nbsp;&nbsp;{frist}{pre}{list}{next}{last}</div>');
        $paginator->setNotActiveTemplate('<a href="{url}">{text}</a>&nbsp;');
        $paginator->setActiveTemplate('<b>{text}</b>&nbsp;');

        $deleteNum = ($page-1) * $pageSize;
        $result = array_slice($result,$deleteNum,$pageSize);
        return ['page'=>$paginator->show(),'result'=>$result];


    }


    public function U($url,$host=false){
        //$router = require "routermap.php";
        if(!isset($this->store['U'])){
            $file = Config::get("router_file");
            $file .= ".php";
            $router = require $file;
            $this->store['U'] = array_flip($router);
        }
        $result = '';
        if(isset($this->store['U'][$url])){
            $result =  $this->store['U'][$url];
        }else{
            $result = $url;
        }

        if($host){
            $result = 'https://'.$_SERVER['HTTP_HOST'].'/'.$result;
        }
        return $result;
    }

    public function alt($key){
        if(!isset($this->store['alt'])){
            $file = Config::get("altmap_file");
            $file .= ".php";
            $this->store['alt'] = require $file;
        }

        if(isset($this->store['alt'][$key])){
            $result =  $this->store['alt'][$key];
        }else{
            $result = "";
        }

        return $result;
    }


}
